import Taro , { Component } from '@tarojs/taro';
import { View, Text , Button, Image} from '@tarojs/components';
import GoodsImage from '../../static/home/banner.png';
import './index.scss';
import { getOrderList, deleteOrder, deliveryOrder, orderCheck, testPay, orderPay } from '../../services/order';
import { ORDER_STATUS } from '../../utils/config';
import NavigationBar from '../../components/navigationBar/index';
import { fullImgUrl } from '../../utils/utils';
import Empty from '../../static/public/icon_order.png';
import UpdateModal from '../../components/update-modal/index';

export default class Index extends Component {

  config = {
      navigationBarTitleText: '我的订单',
      enablePullDownRefresh: true,
  }

  state = {
    isShowUpdateModal: false,
    UpdateOrderInfo: null,
    activeIndex: 0,
    orderList: [],
    pageData: {
      page: 1,
      page_number: 10
    },
    isMore: false,
    tab2order: [-1, 0, 2, 3, 4, 1],
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
  }

  componentWillMount () {
  }
  componentDidMount () {}
  componentWillReceiveProps (nextProps,nextContext) {}
  componentWillUnmount () {}
  componentDidShow () {
    console.log('componentDidShow')
    this.changeTab(this.state.activeIndex);
  }
  componentDidHide () {}
  componentDidCatchError () {}
  componentDidNotFound () {}

  onPullDownRefresh() {
    console.log('pull donw');
    Taro.showLoading({
      mask: true
    })
    this.changeTab(this.state.activeIndex);
  }

  onReachBottom() {
    console.log('reach bottom');
    if (this.state.isMore) {
      getOrderList({
        order_status: this.state.tab2order[this.state.activeIndex],
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let temp = this.state.orderList
        temp = temp.concat(res.list)
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: temp,
          isMore: temp.length < res.total,
          pageData
        })
      })
    }
  }

  changeTab(index, e) {
    this.setState({
      activeIndex: index,
      pageData: {
        page: 1,
        page_number: 10
      },
      isMore: false,
    }, () => {
      getOrderList({
        order_status: this.state.tab2order[index],
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: res.list,
          isMore: res.list.length < res.total,
          pageData
        }, () => {
            Taro.stopPullDownRefresh();
            Taro.hideLoading()
        })
      })
    });
  }

  delOrder(orderId) {
    let self = this;
    Taro.showModal({
      title: '提示',
      content: '删除后不可恢复,你确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          deleteOrder({
            order_info_id: orderId
          }).then(res => {
            let temp = [...self.state.orderList];
            temp = temp.filter(item => {
              return item.order_info_id !== orderId;
            })
            self.setState({
              orderList: temp
            });
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  }

  onScrollToLower = () => {
    console.log('下拉加载更多');
    if (this.state.isMore) {
      getOrderList({
        order_status: this.state.tab2order[this.state.activeIndex],
        ...this.state.pageData
      }).then(res => {
        console.log(res)
        res.list.forEach(item => {
          item.has_order_goods_sku[0].cover = fullImgUrl(item.has_order_goods_sku[0].cover)
        })
        let temp = this.state.orderList
        temp = temp.concat(res.list)
        let pageData = this.state.pageData;
        pageData.page++;
        this.setState({
          orderList: temp,
          isMore: temp.length < res.total,
          pageData
        })
      })
    }
  }

  goOrderDetail(orderId) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/order-detail/index?id=${orderId}`
    })
  }

  applyInvoice(orderId) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/apply-invoice/index?id=${orderId}`
    });
  }

  checkOrder(orderId) {
    orderCheck({
      order_info_id: orderId
    }).then(res => {
      let temp = [...this.state.orderList];
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].order_info_id === orderId) {
          temp[i].order_status = 4;
          break;
        }
      }
      console.log(temp);
      this.setState({
        orderList: temp
      });
    })
  }

  goPay(orderId) {
    let self = this
    orderPay({
      order_id: orderId,
      // pay_type: 1,
      pay_type: 3,
      pay_platform: 1
    }).then(data => {
      Taro.requestPayment({
        // ...data,
        ...(JSON.parse(data.payload).metadata),
        success() {
          self.changeTab(0)
        },
        fail() {
          console.log('not ok')
        }
      })
    })
  }

  checkExpress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/express-status/index?id=${order.order_info_id}`
    })
  }

  update(order) {
    this.setState({
      isShowUpdateModal: true,
      UpdateOrderInfo: order,
    })
  }

  updateAddress(order) {
    Taro.navigateTo({
      url: `/subPackageWork/pages/my-address/index?orderId=${order.order_info_id}`
    });
  }

  cancelModal() {
    this.setState({
      isShowUpdateModal: false,
    })
  }

  render() {
    const tabList = ['全部', '待付款', '待发货', '待收货', '已完成', '已取消'].map((tab, index) => {
      return <View key={index} onClick={this.changeTab.bind(this, index)} className={activeIndex === index ? 'active tab-item' : 'tab-item'}>{tab}</View>
    });
    let { orderList, isShowUpdateModal, UpdateOrderInfo } = this.state;
    return (
      <View className="my-order" style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="我的订单" type="activity"/>
        <View className="tab-list" style={`top: ${navigationBarHeight}`}>{tabList}</View>
        {/* <ScrollView
          className='order-list'
          scrollY
          scrollWithAnimation
          onScrollToLower={this.onScrollToLower}
        > */}
        <View className="order-list">
          {orderList.length ? orderList.map((order, index) => {
            return <View className={'order-card'} key={order.id}>
              <View className="top">
                <View className="order-id">订单号:{order.order_sn}</View>
                <View className="order-status ready-pay">{ORDER_STATUS[order.order_status]}</View>
              </View>
              <View className="middle" onClick={this.goOrderDetail.bind(this, order.order_info_id)}>
                <Image className="goods-image" src={order.has_order_goods_sku[0].cover} alt="商品图" />
                <View className="order-info">
                  <View className="goods-name">{order.has_order_goods_sku[0].goods_name}</View>
                  <View className="goods-desc">{order.has_order_goods_sku[0].has_order_goods_attr.map((attr, index) => {
                    return <Text key={attr.id}>{attr.goods_sku_attr_name + ' '}</Text>;
                  })}</View>
                  <View className="goods-specification">
                    <View className="goods-number">数量: {order.has_order_goods_sku[0].num}</View>
                    <View className="goods-price">¥ {order.paid_amount}</View>
                  </View>
                </View>
              </View>
              <View className="bottom">
                {order.order_status === 0 && <View onClick={this.goPay.bind(this, order.order_info_id)} className="opt-btn to-pay">去支付</View>}
                {order.order_status === 3 && <View className="opt-btn check-order" onClick={this.checkOrder.bind(this, order.order_info_id)}>确认收货</View>}
                {order.order_status === 3 && <View onClick={this.checkExpress.bind(this, order)} className="opt-btn look-logistics">查看物流</View>}
                {order.order_status === 2 && !order.is_update_delivery_time && <View onClick={this.update.bind(this, order)} className="opt-btn update">修改时间</View>}
                {order.order_status === 2 && !order.is_update_address && <View onClick={this.updateAddress.bind(this, order)} className="opt-btn update">修改地址</View>}
                {(order.order_status === 3 || order.order_status === 4 || order.order_status === 2) && !order.is_receipt && <View className="opt-btn request-invoice" onClick={this.applyInvoice.bind(this, order.order_info_id)}>申请发票</View>}
                {(order.order_status === 1 || order.order_status === 4) && <View className="opt-btn del-order" onClick={this.delOrder.bind(this, order.order_info_id)}>删除订单</View>}
              </View>
            </View>
          }) : <View className="empty-box">
            <Image src={Empty} className="empty" />
            <View className="tip">暂无订单信息</View>
          </View> }
        </View>
        {/* </ScrollView> */}
        {isShowUpdateModal && <UpdateModal orderInfo={UpdateOrderInfo} cancel={this.cancelModal.bind(this)} />}
      </View>
    );
  }
}
